'use strict';

const BaseController = require('./base');
const {Op} = require("sequelize");

class CourseController extends BaseController {
  constructor(ctx) {
    super(ctx, 'course');
  }
  getPageQuery(query) {
    const where = {
      status: 1
    };
    const order = []
    if (query.keyword) {
      where[Op.or] = [
        {
          name: {
            [Op.like]: `%${query.keyword}%`
          }
        },
        {
          teacher_name: {
            [Op.like]: `%${query.keyword}%`
          }
        }
      ]
    }
    if (query.grade) {
      where.grade = {
        [Op.like]: `%${query.grade}%`
      }
    }
    if (query.sort) {
      if (query.sort == 1) {
        // 报名人数从高到低
        order.push(['signed_count', 'DESC'])
      }
      if (query.sort == 2) {
        // 报名人数从低到高
        order.push(['signed_count', 'ASC'])
      }
    } else {
      order.push(['create_time', 'DESC'])
    }
    console.log('where',where)
    return {
      where,
      order
    }
  }
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize } = query;
    let page = Number(pageNum) || 1;
    let size = Number(pageSize) || 10;
    delete query.pageNum
    delete query.pageSize
    const list = await service[this.serviceName].getPage(this.getPageQuery(query).where, page, size, this.getPageQuery(query).order);
    this.ctx.success(list);
  }
}

module.exports = CourseController;
